from flask import Blueprint,jsonify,make_response,redirect
import requests
from db import db
import datetime
from utils.send_code import send_message
import json
from utils.captcha.captcha import captcha
from utils.myredis import r
import redis

from flask import current_app as app,request
login_blue = Blueprint('login_blue',__name__)




@login_blue.route('/getimg')
def get_img():
    name,text,img=captcha.generate_captcha()
    uuid=request.args.get('uuid')
    print("uuid4444>>>>",uuid)
    r.str_add(uuid,text)
    print("uuid4444>>>>", uuid)
    print("rrrrrr>>>>>>>>>",r.str_get(uuid))
    cls = redis.Redis(host='127.0.0.1')
    print(">>>>>>>>>>>>>>>>",cls.get(uuid))
    res=make_response(img)
    res.headers['Content-Type']="image/jpg"
    return res

import json
@login_blue.route('/smscode',methods=['POST'])
def smscode():
    # 接收前端传来的参数
    data=json.loads(request.data)
    mobile=data['mobile']
    code=data['code']
    uuid=data['uuid']
    print("uuid>>>>>",uuid)
    # 判断参数是否完整
    if not all([mobile,code,uuid]):
        return jsonify({"code":"400","msg":"参数不完整"})
    # 从redis中获取图片验证码
    cls=redis.Redis(host="127.0.0.1")
    code1=cls.get(uuid)
    print(".........",code)
    print("--------",code)
    # code=r.str_get(uuid)
    print("code>>>>",code)
    # 如果获取到了
    if code1:
        # 就让前端的验证码和后端redis中的验证码做对比 然后转换成小写
        if code.lower() != code1.decode().lower():
            return jsonify({"code":"401","msg":"图片验证码错误"})
        # 清除redis中的图片验证码
        r.del_key(uuid)
    # 如果没获取到就返回没有
    else:
        return jsonify({"code":400,"msg":"没有获取到图片验证码"})
    v=r.str_get(mobile)
    if v:
        return jsonify({"code":20014,"msg":"一分钟内只能发一次"})
    r.list_push("smsmobile",mobile)
    return jsonify({"code":200})

import time
import random
@login_blue.route('/sms')
def send():
    while True:
        # 查看队列长度如果没有值不处理
        for i in range(2):
            len=r.list_len("smsmobile")
            if len > 0:
                value =r.list_pop("smsmobile")
                mobile=value.decode()
                code=random.randint(1000,9999)
                res=send_message(mobile,code)
                print(res)
                r.str_setex(mobile,code,300)

        time.sleep(3)

from utils.my_jwt import jj
@login_blue.route('/login',methods=['POST'])
def login():
    # 接收前端参数
    data=json.loads(request.data)
    mobile=data['mobile']
    sms_code=data['sms_code']
    # 从redis中取出验证码
    cls=redis.Redis(host="127.0.0.1")
    codemes=cls.get(mobile)
    print("codemes>>>>>>",codemes)
    # 如果获取到了
    if codemes:
        # 将前端传来的参数和redis中的验证码做对比
        if str(codemes.decode()) != str(sms_code):
            return jsonify({"code":400,"msg":"验证码错误"})
        # 调用完后释放系统资源
        r.del_key(mobile)
        # 使用原生sql查询数据库中的手机号和前端的是否一致 如果有的话就生成token登录
        sql = "select id from users where mobile='%s'"%(mobile)
        user=db.find(sql)
        # 如果查询到了 就编写token 返回token
        if user:
            data={"data":{"userid":user['id'],"mobile":['mobile']}}
            token=jj.jwt_encode(data)
            return jsonify({"code":200,"token":token,"userid":user['id']})
        # 否则就提示没有此用户不能登录
        else:
            return jsonify({"code":10034,"msg":"没有此用户不能登录"})
    # 如果没有获取到验证码 就是已过期
    else:
        return jsonify({"code":10031,"msg":"验证码已过期"})









# 添加推广获取链接
@login_blue.route("/setspread", methods=["POST"])
def setspread():
    data = json.loads(request.data)
    link = "http://localhost:8080/?c="+data["code"]
    print("link", link)
    print("rate", float(data["rate"]))
    rate = float(data["rate"])
    sql = "insert into spread(name,code,rate,link) values('%s','%s','%s','%s')" % (
        data["name"], data["code"], rate, link)
    db.add(sql)
    db.commit()
    return jsonify({"code": 200, "link": link})

# 添加访问记录
@login_blue.route("/setaccessrecord", methods=["POST"])
def setaccessrecord():
    data = json.loads(request.data)
    source=data["source"]
    print("source",source)
    add_date = datetime.datetime.strftime(
        datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    # 1分钟只能发送一次
    v = r.str_get(data["ip"])
    if v:
        return jsonify({"code": 400, "msg": "1分钟只能发送一次"})
    else:
        sq2 = "select * from access_record where source='%s'" % (
            data["source"])
        red = db.find(sq2)
        if red:
            number = int(red["number"])
            number+=1
            sql3 = "update access_record set number=%d where source='%s'"%(number, source)
            db.add(sql3)
            db.commit()
            r.str_setex(data["ip"], data["ip"], 60)
        else:
            sql = "insert into access_record(ip,source,add_date,number) values('%s','%s','%s',%d)" % (
                data["ip"], data["source"], add_date, 1)
            db.add(sql)
            db.commit()
            r.str_setex(data["ip"], data["ip"], 60)
    return jsonify({"code": 200, "msg": "ok"})

# 获取每个公司的总金额
@login_blue.route("/addcount")
def addcount():
    sql1 = "select a.number*s.rate as price, s.name from access_record as a inner join spread as s on s.link = a.ip"
    res = db.find_all(sql1)
    lst = [{"value":int(i["price"]),"name":i["name"]}for i in res]
    return jsonify({"code": 200, "data": lst})





# 添加工作流程
@login_blue.route('/addwork',methods=['POST'])
def addwork():
    data=json.loads(request.data)
    name=data['name']
    sql="insert into work(name) value('%s')"%(name)
    db.add(sql)
    db.commit()
    return jsonify({"code":200})




# 获取流程
@login_blue.route('/getwork')
def getwork():
    sql="select * from work"
    res=db.find_all(sql)
    return jsonify({"code":200,"list":res})


# 配置字段
@login_blue.route('/updateparams',methods=['POST'])
def updateparams():
    data=json.loads(request.data)
    wid=int(data['wid'])
    params=data['params']
    sql="update work set params='%s' where id=%d"%(params,wid)
    db.add(sql)
    db.commit()
    return jsonify({"code":200})

